package org.xmlParser;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;


public class xmlReader {

	public static String xmlFromUrl(String url){
		StringBuffer sb = new StringBuffer();
		try{	
		URL oracle = new URL(url);
		
		HttpURLConnection connection = (HttpURLConnection) oracle
				.openConnection();
	
		connection.setRequestMethod("GET");
		connection.setRequestProperty("Content-Type", "text/xml");

		// URLConnection yc = oracle.openConnection();
		// yc.setReadTimeout(100000);
		BufferedReader in = new BufferedReader(new InputStreamReader(
				connection.getInputStream()));
		String inputLine;
		



		while ((inputLine = in.readLine()) != null)
			sb.append(inputLine);		
		in.close();
		
		}catch(Exception e){}

		
		return sb.toString();
	}
	
	public static String xmlFromFile(String file){
		StringBuffer sb=new StringBuffer();
		
		try {
		      FileInputStream fstream = new FileInputStream(file);
		      DataInputStream in = new DataInputStream(fstream);
		      BufferedReader br = new BufferedReader(new InputStreamReader(in));
		      String str;
		      while ((str = br.readLine()) != null) {
		        sb.append(str);
		      }
		      in.close();
		    } catch (Exception e) {
		      System.err.println(e);
		    }
		return sb.toString();
	}
	
	public static Document loadXMLFromString(String xml) throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		InputSource is = new InputSource(new StringReader(xml));
		return builder.parse(is);
	}
	
	public static String getAtributeValue(String sTag, Element eElement, String attribute, String property) {
		String out = "";
		NodeList links = eElement.getElementsByTagName(attribute);
		for (int i = 0; i < links.getLength(); i++) {
			Element link = (Element) links.item(i);
			String abc = link.getAttribute(property);
			if (sTag.compareTo(abc) == 0) {
				out = link.getFirstChild().getNodeValue();
			}
		}
		return out;
	}
	public static Document createDocUrl(String url)throws Exception{
		
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		
		Document doc = xmlReader.loadXMLFromString(xmlReader.xmlFromUrl(url));
		
		return doc;
	}
	
	
}
